package com.hst.capacity.infra.web.config;

import com.alibaba.fastjson2.JSON;
import com.hst.capacity.domain.enums.Rep;
import com.hst.capacity.domain.model.response.DefaultVO;
import com.hst.capacity.facade.filter.TokenAuthenticationFilter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;

@Configuration
@EnableWebSecurity
@EnableConfigurationProperties(BrandTokenProperties.class)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    /*@Value("${capacity.token.switch}")
    private boolean tokenSwitch;

    @Value("${capacity.authorize.enable}")
    private boolean authorizeEnable;*/

    final BrandTokenProperties tokenProperties;

    public WebSecurityConfiguration(BrandTokenProperties capacityTokenProperties) {
        this.tokenProperties = capacityTokenProperties;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // super.configure(http);
        http
                .csrf().disable()
                // 不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        if (tokenProperties.getAuthorize()) {
            // 访问权限配置
            http.authorizeHttpRequests(authorize -> authorize
                    .mvcMatchers("/auth/**").permitAll()
                    .mvcMatchers("/alitrip/transfer/**").permitAll()
                    .mvcMatchers("/agent/search").hasRole("B_ADMIN")
                    .anyRequest().denyAll()
            )
                    .exceptionHandling()
                    .accessDeniedHandler((req, resp, authException) -> {
                                resp.setContentType("application/json;charset=utf-8");
                                resp.setStatus(401);
                                PrintWriter out = resp.getWriter();
                                out.write(JSON.toJSONString(DefaultVO.error(Rep.UNAUTHORIZED)));
                                out.flush();
                                out.close();
                            }
                    );
        }

        // 添加Token验证过滤器
        if (tokenProperties.getEnable())
            http.addFilterBefore(new TokenAuthenticationFilter(tokenProperties), UsernamePasswordAuthenticationFilter.class);

        http.httpBasic().disable();
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /*@Profile("prod")
    @Bean
    public CorsFilter corsFilter() {
        //1. 添加 CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOrigin("http://capacity.hst.amading.com");
        //是否发送 Cookie
        config.setAllowCredentials(true);
        //放行哪些请求方式
        config.addAllowedMethod("*");
        //放行哪些原始请求头部信息
        config.addAllowedHeader("*");
        //暴露哪些头部信息
        config.addExposedHeader("*");
        //2. 添加映射路径
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**",config);
        //3. 返回新的CorsFilter
        return new CorsFilter(corsConfigurationSource);
    }*/

    @Profile(value = {"prod", "staging"})
    @Bean("passwordEncoder")
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Profile("dev")
    @Bean("passwordEncoder")
    public PasswordEncoder passwordEncoderDev() {
        return NoOpPasswordEncoder.getInstance();
    }
}
